package com.example.nfcapplication;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.NfcA;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.nfcapplication.utils.Utils;


@SuppressLint("NewApi")
public class ReadTag extends AppCompatActivity {
    private NfcAdapter nfcAdapter;
    private TextView resultText;
    private PendingIntent pendingIntent;
    private IntentFilter[] mFilters;
    private String[][] mTechLists;
    private Button mJumpTagBtn;
    private boolean isFirst = true;

    public static void startActivity(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, ReadTag.class);
        context.startActivity(intent);
    }

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (nfcAdapter == null) {
            Toast.makeText(this, getResources().getString(R.string.no_nfc),
                    Toast.LENGTH_SHORT).show();
            finish();
            return;
        } else if (!nfcAdapter.isEnabled()) {
            Toast.makeText(this, getResources().getString(R.string.open_nfc),
                    Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        setContentView(R.layout.read_tag);
        //
        resultText = (TextView) findViewById(R.id.resultText);
        //
        mJumpTagBtn = (Button) findViewById(R.id.jump);
        mJumpTagBtn.setOnClickListener(new WriteBtnOnClick());

        pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
                getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        ndef.addCategory("*/*");
        mFilters = new IntentFilter[]{ndef};//
        mTechLists = new String[][]{
                new String[]{MifareClassic.class.getName()},
                new String[]{NfcA.class.getName()}};//

    }

    @SuppressLint("NewApi")
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        nfcAdapter.enableForegroundDispatch(this, pendingIntent, mFilters,
                mTechLists);
        if (isFirst) {
            if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(getIntent().getAction())) {
                String result = processIntent(getIntent());
                resultText.setText(result);
            }
            isFirst = false;
        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub
        super.onNewIntent(intent);
        if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
            String result = processIntent(intent);
//            resultText.setText(result);
        }
    }

    /**
     * @param intent
     * @return
     */
    @SuppressLint("NewApi")
    private String processIntent(Intent intent) {
        readCardCode(intent);
        readCardDataM1(intent);
        /*Parcelable[] rawmsgs = intent
                .getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        NdefMessage msg = (NdefMessage) rawmsgs[0];
        NdefRecord[] records = msg.getRecords();
        String resultStr = new String(records[0].getPayload());*/
        return "resultStr";
    }

    /**
     * 读M1卡数据
     */
    private void readCardDataM1(Intent intent) {
        StringBuilder msgBuffer = new StringBuilder();
        String action = intent.getAction();
//        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        MifareClassic mifareClassic = MifareClassic.get(tag);
        try {
            mifareClassic.connect();
            //获取扇区数量
            int count = mifareClassic.getSectorCount();
            Log.e("onNewIntent:", "扇区数量 ===" + count);
            //用于判断时候有内容读取出来
            for (int i = 0; i < count; i++) {
//					boolean isOpen = mifareClassic.authenticateSectorWithKeyA(i, MifareClassic.KEY_DEFAULT);
                boolean isOpen = mifareClassic.authenticateSectorWithKeyA(i, new byte[]{(byte) 0xD0, (byte) 0xC1, (byte) 0xBF, (byte) 0x97, (byte) 0xA0, 0x2C});
                if (isOpen) {
                    //获取扇区里面块的数量
                    int bCount = mifareClassic.getBlockCountInSector(i);
                    Log.e("onNewIntent:", "扇区里面块的数量 ===" + bCount);
                    //获取扇区第一个块对应芯片存储器的位置
                    //存储器的位置为第一扇区为0后面叠加4直到60为止
                    int bIndex = mifareClassic.sectorToBlock(i);
                    for (int j = 0; j < bCount; j++) {
                        Log.e("onNewIntent:", "存储器的位置 ===" + bIndex + "当前块 === " + (bIndex + j));
                        byte[] data = mifareClassic.readBlock(bIndex + j);//进行了读卡
                        msgBuffer.append("块" + (bIndex + j) + "数据:").append(Utils.bytesToHexString(data)).append("\r\n");
                        msgBuffer.append(new String(Utils.hexStringToByteArray(Utils.bytesToHexString(data)),"GBK"));
//							handler.sendEmptyMessage(0);
                        Log.e("数据", "第" + (bIndex + j) + "块" + Utils.bytesToHexString(data));

                        //修改KeyA和KeyB
							/*if ((bIndex+j)==(4*i+3)){
								//将所有扇区的最后一个Block修改为111111111111ff078069111111111111
								mifareClassic.writeBlock(bIndex+j,new byte[]{(byte) 0x11, (byte) 0x11, (byte) 0x11, (byte) 0x11, (byte) 0x11, (byte) 0x11, (byte) 0xff, 0x07, (byte) 0x80, (byte) 0x69,(byte) 0x11, (byte) 0x11, (byte) 0x11, (byte) 0x11, (byte) 0x11, (byte) 0x11});
								Log.e("onNewIntent:",(bIndex+j)+"块加密成功");

							}*/

                    }
                }
            }
            resultText.setText(msgBuffer);
        } catch (Exception e) {

        }
//        }else {
//			msgBuffer.append("第"+(i+1)+"扇区"+"验证新卡密码失败\r\n");
//			handler.sendEmptyMessage(0);
//			Log.e("失败 ","验证密码");
//		}
    }

    /**
     * @param intent 读nfc卡号
     */
    private void readCardCode(Intent intent) {
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        if (tag != null) {
            byte[] bytCardSN = tag.getId();
            if (bytCardSN != null) {
                String strCardSN = Utils.bytesToHexString(bytCardSN);   //读取到卡号
                Log.i("### NFC", "卡号为:" + strCardSN);
                Toast.makeText(this, "卡号:" + strCardSN, Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 按钮点击事件
     */
    class WriteBtnOnClick implements OnClickListener {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
                case R.id.jump:
                    Intent intent = new Intent(ReadTag.this, WriteTag.class);
                    startActivity(intent);
                default:
                    break;
            }
        }

    }

}
